/**
 * Created by cyf on 15-12-1.
 * 聊天窗口
 */
var qxchat;
//当前聊天窗口用户
var groupId;
var groupName;
//当前登录用户
var fromUserLoginName;
var fromUserName;

//初始化
$(function() {
    new qxchat.WindowSize();
    document.title = groupName;
    $(".qx-chat-t-name").html(groupName);
    //发送消息
    $('.fasong').click(sendMessage)

    $('#qx-chat-text').keydown(function(e) {
        if (e.keyCode == 13) {
            sendMessage();
        }
    })
    $('#qx-chat-text').focus();
    // 绑定表情
    $('#face').SinaEmotion($('#qx-chat-text'));
    // 读取未读
    var message = '{"data":{"groupId":"' + groupId + '","chatType":1},"type":"noReadMsg"}';
    global.webSocketHandler.send(message);
});

//显示消息
function receiveLog(data) {
    var name = data.fromName;
    var ner = $.base64.decode(data.msg);
    var ners = ner.replace(/\n/g, '<br>')
    var tl = Number(data.time);
    var now = new Date(tl);
    ners = AnalyticEmotion(ners);
    var t_div = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + ' ' + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
    $('.qx-chat-txt ul').append('<li class="my"><div class="qx-chat-you blue"><span>' + name + '</span><i>&#12288;' + t_div + '</i></div><div class="qx-chat-ner">' + ners + '</div></li>')
    $(".qx-chat-txt").scrollTop($(".qx-chat-txt")[0].scrollHeight);
    $('#qx-chat-text').val('').trigger("focus")
    $('#qx-chat-text').focus();
    //通知后台消息已读
    var message = '{"data":{"id":"' + data.id + '"},"type":"readMsg"}';
    global.webSocketHandler.send(message);
}

//发送消息
var sendMessage = function() {
    if ($('#qx-chat-text').val() != '') {
        var name = fromUserName;
        var ner = $('#qx-chat-text').val()
        var ners = ner.replace(/\n/g, '<br>')
        var now = new Date();
        ners = AnalyticEmotion(ners);
        if (global.webSocketHandler != null) {
            var message = $.base64.encode(ner);
            message = '{"data":{"from":"' + fromUserLoginName + '","fromName":"' + fromUserName + '","msg":"' + message + '","to":"' + groupId + '","toName":"' + groupName + '","groupId":"' + groupId + '","groupName":"' + groupName + '"},"type":"groupMsg"}';
            global.webSocketHandler.send(message);
        } else {
            alert('connection not established, please connect.');
        }
        var t_div = now.getFullYear() + "-" + (now.getMonth() + 1) + "-" + now.getDate() + ' ' + now.getHours() + ":" + now.getMinutes() + ":" + now.getSeconds();
        $('.qx-chat-txt ul').append('<li class="my"><div class="qx-chat-my"><span>' + name + '</span><i>&#12288;' + t_div + '</i></div><div class="qx-chat-ner">' + ners + '</div></li>')
        $(".qx-chat-txt").scrollTop($(".qx-chat-txt")[0].scrollHeight);
        $('#qx-chat-text').val('').trigger("focus");
        $('#qx-chat-text').focus();
    }
}

// 文件下载
function downLoadFile(fileId, targetPath) {
    $("#" + fileId + "_text").html('文件接收中...<img src="imgs/fileloading.gif">');
    var fs = require('fs');
    var request = require('request');
    var fileWriteStream = fs.createWriteStream(targetPath);
    var sourceFilePath = $("#" + fileId + "_path").val();
    request(sourceFilePath).pipe(fileWriteStream);
    fileWriteStream.on('finish', function() {
        $("#" + fileId + "_text").html('接收完成！文件路径：' + targetPath);
    });
    fileWriteStream.on('error', function() {
        $("#" + fileId + "_text").html('接收失败，请重试！');
    });
}

// 文件发送
jQuery(function() {
    var $ = jQuery,
        $list = $('#thelist'),
        state = 'pending',
        baseUrl = 'http://' + global.serverPath + ':' + global.serverPort,
        uploader;

    uploader = WebUploader.create({

        // 自动上传。
        auto: true,

        // 不压缩image
        resize: false,

        // 文件接收服务端。
        server: baseUrl + '/file/uploadFile',

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建，可能是input元素，也可能是flash.
        pick: '#picker'
    });

    // 当有文件添加进来的时候
    uploader.on('fileQueued', function(file) {
        $list.append('<li id="' + file.id + '" class="my qx-chat-ner">' +
            '<div class="green">' + file.name + '</div>' +
            '<p class="green state">等待发送...</p>' +
            '</li>');
    });

    // 文件上传过程中创建进度条实时显示。
    uploader.on('uploadProgress', function(file, percentage) {
        var $li = $('#' + file.id),
            $percent = $li.find('.progress .progress-bar');

        // 避免重复创建
        if (!$percent.length) {
            $percent = $('<div class="progress progress-striped active">' +
                '<div class="progress-bar" role="progressbar" style="width: 0%">' +
                '</div>' +
                '</div>').appendTo($li).find('.progress-bar');
        }

        $li.find('p.state').text('发送中');

        $percent.css('width', percentage * 100 + '%');
    });

    uploader.on('uploadSuccess', function(file, e) {
        $('#' + file.id).find('p.state').text('已发送');
        //通知对方
        var message = '文件名：' + file.source.name;
        message += '    <a href="javascript:;" class="qx-chat-file">';
        message += '<input id="' + file.id + '_path" type="hidden" value="' + e._raw + '">';
        message += '另存为';
        message += '<input id="' + file.id + '_fileDialog" type="file" nwsaveas="' + file.source.name + '" onchange="downLoadFile(\'' + file.id + '\',this.value)"/>';
        message += '</a>';
        message += '</br>';
        message += '<p id="' + file.id + '_text" class="green"></p>';
        message = $.base64.encode(message);
        message = '{"data":{"from":"' + fromUserLoginName + '","fromName":"' + fromUserName + '","msg":"' + message + '","to":"' + groupId + '","toName":"' + groupName + '"},"type":"msg"}';
        global.webSocketHandler.send(message);
    });

    uploader.on('uploadError', function(file) {
        $('#' + file.id).find('p.state').text('发送出错');
    });

    uploader.on('uploadComplete', function(file) {
        $('#' + file.id).find('.progress').fadeOut();
    });

    uploader.on('all', function(type) {
        if (type === 'startUpload') {
            state = 'uploading';
        } else if (type === 'stopUpload') {
            state = 'paused';
        } else if (type === 'uploadFinished') {
            state = 'done';
        }
    });
});

/**
 * Created by cyf on 15-12-1.
 * 初始化窗口的三个按钮
 */
(function() {
    qxchat.WindowSize = WindowSize;
    var EXTEND = null; //是否需要继承
    function WindowSize() {
        if (EXTEND) {
            EXTEND.apply(this, arguments);
        }
        this._sizeFlag = true;
        this._gui = require('nw.gui');
        this._win = this._gui.Window.get();
        this.init();
        var self = this;
        $('.min').bind('click', function() {
            self.minimize();
        });
        $('.max').bind('click', function() {
            self.maxToggle();
        });
        $('.close').bind('click', function() {
            self.close();
        });
        $('.close-chat').click(function() {
            self.close();
        })
        $(document).keydown(function(event) {
            if (event.altKey && event.keyCode == 67) {
                self.close();
            };
            if (event.altKey && event.keyCode == 83) {
                sendMessage();
            };
        });

    }
    WindowSize.prototype = {
        constructor: WindowSize,
        init: function() {

        },
        minimize: function() {
            this._win.minimize();
            this._sizeFlag = true;
        },
        maxToggle: function() {
            if (this._sizeFlag) {
                this._win.maximize();
                this._sizeFlag = false;
            } else {
                this._win.unmaximize();
                this._sizeFlag = true;
            }
        },
        close: function() {
            this._win.close();
        }
    }
})();